import sys
import os
import re
import ConfigParser
import logging
from optparse import OptionParser
import subprocess
import zipfile
import glob, os
import datetime
import globalvar
import pprint
import shutil 
import traceback

    
def main(*argv):
    """Generate the dm package using the """
    if argv:
        argv = list(argv)
    else:
        argv = sys.argv[1:]
        
    usage = "usage: mkotopl.py -i <your_config.ini>"
    
    if(len(argv) == 0):
        print usage     
        exit(-1)
        
    parser = OptionParser(usage=usage)
    parser.add_option("-i", "--configfile", dest="configfile",type="string",help="configfile")

    (options, args) = parser.parse_args(args=argv)
    
    configfile = None
    
    if options.configfile:
        configfile = os.path.abspath(options.configfile)       

    config = ConfigParser.ConfigParser()
    config.read(configfile)
    
    globalvar.VENDOR = config.get("Basic","vendor")
    globalvar.RELEASE = config.get("Basic","release")    
    globalvar.MODEL = config.get("Basic","model")
    globalvar.PIM_UA = config.get("Basic","PIM_User_Agent")
    globalvar.BROWSER_UA = config.get("Basic","Browser_User_Agent")
    globalvar.MOBILE_MUSIC_UA = config.get("Basic","MobileMusic_Default_User_Agent")   

    globalvar.otlogging.debug("vendor : %s"%(globalvar.VENDOR))
    globalvar.otlogging.debug("release : %s"%(globalvar.RELEASE))
    globalvar.otlogging.debug("model : %s"%(globalvar.MODEL))
    globalvar.otlogging.debug("PIM_User_Agent : %s"%(globalvar.PIM_UA))
    globalvar.otlogging.debug("Browser_User_Agent : %s"%(globalvar.BROWSER_UA))
    globalvar.otlogging.debug("MobileMusic_Default_User_Agent : %s"%(globalvar.MOBILE_MUSIC_UA))

    out_dir="%s_%s"%(globalvar.VENDOR,globalvar.MODEL)
    if(os.path.isdir(out_dir)):
        shutil.rmtree(out_dir,ignore_errors=True)

    shutil.copytree( "res",out_dir)
    vendor_pattern = re.compile(r'apps.setting.product.vendor\s{0,}\=\s{0,}(.*)')
    vendor_pattern_replace ='apps.setting.product.vendor=%s'%(globalvar.VENDOR)
    
    inf=open('./%s/system.prop'%(out_dir),'r')    
    all_str=inf.read()
    inf.close()
    
    out_str=re.sub(vendor_pattern,vendor_pattern_replace,all_str)
        

    
    release_pattern = re.compile(r'apps.setting.product.release\s{0,}\=\s{0,}(.*)')
    release_pattern_replace = 'apps.setting.product.release=%s'%(globalvar.RELEASE)    
    out_str=re.sub(release_pattern,release_pattern_replace,out_str)    
    
    model_pattern = re.compile(r'apps.setting.product.model\s{0,}\=\s{0,}(.*)')
    model_pattern_replace = 'apps.setting.product.model=%s'%(globalvar.MODEL)
    out_str=re.sub(model_pattern,model_pattern_replace,out_str)
    
    outf=open('./%s/system.prop'%(out_dir),'w')
    outf.write(out_str)
    outf.close()
    
    
    pim_ua_pattern = re.compile(r'<entry key\=\"user_agent\">(.*)</entry>')
    pim_ua_pattern_replace = '<entry key\=\"user_agent\">%s</entry>'%(globalvar.PIM_UA)
    
    inf=open('./%s/syncml_ds_dev_info.xml'%(out_dir),'r')    
    all_str=inf.read()
    inf.close()
    
    out_str=re.sub(pim_ua_pattern,pim_ua_pattern_replace,all_str)        
    outf=open('./%s/syncml_ds_dev_info.xml'%(out_dir),'w')    
    outf.write(out_str)
    outf.close()
    
    browser_ua_pattern = re.compile(r'<user_agent_key>(.*)<\/user_agent_key>')
    browser_ua_pattern_replace = '<user_agent_key>%s<\/user_agent_key>'%(globalvar.BROWSER_UA)

    inf=open('./%s/properties.xml'%(out_dir),'r')    
    all_str=inf.read()
    inf.close()
    
    out_str=re.sub(browser_ua_pattern,browser_ua_pattern_replace,all_str)        
    outf=open('./%s/properties.xml'%(out_dir),'w')    
    outf.write(out_str)
    outf.close()

    
    mobile_music_ua_pattern = re.compile(r'<MobileMusic_DefaultUA>(.*)</MobileMusic_DefaultUA>')
    mobile_music_ua_pattern_replace = '<MobileMusic_DefaultUA>%s</MobileMusic_DefaultUA>'%(globalvar.MOBILE_MUSIC_UA)
    inf=open('./%s/mobilemusic.xml'%(out_dir),'r')    
    all_str=inf.read()
    inf.close()
    
    out_str=re.sub(mobile_music_ua_pattern,mobile_music_ua_pattern_replace,all_str)        
    outf=open('./%s/mobilemusic.xml'%(out_dir),'w')    
    outf.write(out_str)
    outf.close()
    



    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = subprocess.SW_HIDE

    error=0
    dirList=os.listdir(out_dir)
    globalvar.otlogging.info("---------------------------Start to use adb to push file to device---------------------------")
    for fname in dirList:        
        if("svn" not in fname):
            globalvar.otlogging.debug("adb push %s /opt/etc/."%(fname))
            adbPopen = subprocess.Popen(('adb','push','%s'%(fname),"/opl/etc/."), stdout=subprocess.PIPE,stderr=subprocess.PIPE, startupinfo = startupinfo)
            adbPopen.wait()
            adbstr = adbPopen.stdout.read()     
            if adbstr!="" :  
                globalvar.otlogging.info(adbstr)
                
            adbstr = adbPopen.stderr.read()
            if adbstr!="":
                error=1      
                globalvar.otlogging.error(adbstr)
                break
    globalvar.otlogging.info("---------------------------End to use adb to push file to device---------------------------")        
    if error == 0:
        globalvar.otlogging.info("Finished OK!")
    else:
        globalvar.otlogging.error("Error, please check your device or config file")    
    
if __name__ == "__main__":
    
    logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s  %(levelname)-8s %(message)s',
                    filename="mkopttool.log",
                    datefmt="%m-%d %H:%M:%S",        
                    filemode='a')

    console=logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    globalvar.otlogging = logging.getLogger('DM')

    try:
        main()
    except:
        exption_str=traceback.format_exc()
        globalvar.otlogging.error( "Unexpected error:\n %s ",exption_str )
    